package com.baomidou.kisso.oauth2;

import cn.hutool.json.JSONUtil;
import com.baomidou.kisso.oauth2.entity.Status;
import org.apache.commons.lang.StringUtils;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Oauth2Filter implements Filter {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse res = (HttpServletResponse) response;

        try {
            //构建OAuth资源请求
            OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest((HttpServletRequest) request, ParameterStyle.QUERY); // queryString 方式获取参数
            // OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest((HttpServletRequest) request, ParameterStyle.HEADER); // 从HttpHead头中获取参数

            String accessToken = oauthRequest.getAccessToken();

            //验证Access Token
            if (!this.checkAccessToken(request, accessToken)) {
                // 如果不存在/过期了，返回未验证错误，需重新验证
                this.oAuthFaileResponse(res);
            } else {
                chain.doFilter(request, response);
            }

        } catch (OAuthProblemException e) {

            try {
                this.oAuthFaileResponse(res);
            } catch (OAuthSystemException ex) {
                logger.error("error trying to access oauth server", ex);
            }

        } catch (OAuthSystemException e) {
            logger.error("error trying to access oauth server", e);
        }

    }


    /**
     * oAuth认证失败时的输出
     *
     * @param res
     * @throws OAuthSystemException
     * @throws IOException
     */
    private void oAuthFaileResponse(HttpServletResponse res) throws OAuthSystemException, IOException {

        OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                .setRealm(Constants.RESOURCE_SERVER_NAME).setError(OAuthError.ResourceResponse.INVALID_TOKEN)
                .buildHeaderMessage();

        //HttpHeaders responseHeaders = new HttpHeaders();
        //responseHeaders.add("Content-Type", "application/json; charset=utf-8");

        res.setContentType("application/json; charset=utf-8");
        res.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
        PrintWriter writer = res.getWriter();
        writer.write(JSONUtil.toJsonStr(getStatus(HttpStatus.UNAUTHORIZED.value(), Constants.INVALID_ACCESS_TOKEN)));
        writer.flush();
        writer.close();

    }


    /**
     * 验证accessToken
     *
     * @param accessToken
     * @return
     * @throws IOException
     */
    private boolean checkAccessToken(ServletRequest request, String accessToken) throws IOException {

        HttpServletRequest req = (HttpServletRequest) request;

        String str1 = req.getRequestURL().toString();
        String str2 = req.getContextPath();

        StringBuffer buffer = new StringBuffer();
        buffer.append(StringUtils.substring(str1, 0, (str1.indexOf(str2) + str2.length())));
        buffer.append("/checkAccessToken?accessToken=");
        buffer.append(accessToken);

        logger.info("checkAccessToken:" + accessToken);

        URL url = new URL(buffer.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //conn.setRequestMethod("POST");
        int code = conn.getResponseCode();
        conn.disconnect();

        return HttpServletResponse.SC_OK == code;
    }


    private Status getStatus(int code, String msg) {
        Status status = new Status();
        status.setCode(code);
        status.setMsg(msg);
        return status;
    }


    @Override
    public void destroy() {

    }


}
